package org.psyduck.admin.user.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.psyduck.admin.user.entity.UserRole;
import org.psyduck.common.base.BaseService;
import org.psyduck.security.dao.UserDao;
import org.psyduck.security.model.User;
import org.psyduck.security.service.SecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService extends BaseService<UserDao, User> {

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    SecurityUserService securityUserService;

    @Transactional
    public boolean save(User user, String roles){
        if(StrUtil.isNotBlank(user.getPassword())){
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        }
        boolean userCount = this.saveOrUpdate(user);
        userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
        String[] roleArr = roles.split(",");
        for (int i = 0; i < roleArr.length; i++) {
            String role = roleArr[i];
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(role);
            userRoleService.save(userRole);
        }
        return userCount;
    }

    @Transactional
    public boolean delete(String id){
        userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", id));
        return this.removeById(id);
    }

    public List<GrantedAuthority> getCurrentUserAuthorities(String userId){
        return securityUserService.getCurrentUserAuthorities(userId);
    }

}